package com.gljx.web.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gljx.util.CommonExport;
import com.gljx.web.Entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gljx.util.GetFid;
import com.gljx.util.GetFnumber;
import com.gljx.util.TimeFormat;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.MaintainItemService;
import com.gljx.web.service.RepairShopService;

@Controller
@RequestMapping("/")
public class MaintainItemController {
	
	//自动注入
	@Autowired
	private MaintainItemService maintainItemService;
	
	//自动注入
	@Autowired
	private RepairShopService repairShopService;

	//自动注入
	@Autowired
	private DepartmentService departmentService;
	
	//自动注入
	@Autowired
	private CustomLogService customLogService;
	
	/**
	 * 查询维修项目
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryMaintainItem/look.action")
    public String queryMaintainItem(HttpServletRequest request, String flag) {
        PageBean<MaintainItem>pb = new PageBean<>();
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
	    try {
			//获取分页
            pb = getPageBean(request, user.getFcompanyid(), null);
            //获取当前分页的值
			List<MaintainItem>maintainItems = pb.getBeanList();
			//把获取到的数据传回页面
			request.setAttribute("maintainItems", maintainItems);
			request.setAttribute("pb", pb);
            request.setAttribute("flag", flag);
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return "/backHome/basicData/maintainItem/maintainItemList";
	}
	
	/**
	 * 跳转到添加页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/insertMaintainItem")
	public String insertMaintainItem(HttpServletRequest request,String type){
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
		//获取上一个编码
        /*String number = maintainItemService.selectFnumber(user.getFcompanyid());*/
		//获取编码
        String fnumber = GetFnumber.fnumbers("WXXM");
		//获取所有的修理厂
		List<RepairShop> repairShops = repairShopService.queryRepairShopAll();
		//获取组织
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//把数据传到页面
		request.setAttribute("fnumber", fnumber);
		request.setAttribute("repairShops", repairShops);
		request.setAttribute("department", department);
		request.setAttribute("type", type);
		return "/backHome/basicData/maintainItem/add";
	}
	
	/**
	 * 添加项目维修
	 * @param request
	 * @param maintainItem 属性自动封装
	 * @return 返回查询
	 */
	@RequestMapping("/addMaintainItem")
	public String addMaintainItem(HttpServletRequest request,MaintainItem maintainItem){
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
	    //利用UUID生成fid
	    maintainItem.setFid(GetFid.UUIDIntoFid());
	    //公司id
	    maintainItem.setCfficompanyid(user.getFcompanyid());
		//控制单元id
	    maintainItem.setFcontrolunitid(user.getFcompanyid());
		//创建人id
	    maintainItem.setFcreatorid(user.getFid());
	    //获取当前时间
	  	String createTime = TimeFormat.timeFormat(new Date());
	  	//当前创建时间
	  	maintainItem.setFcreatetime(createTime);
	    //完成添加
	  	maintainItemService.addMaintainItem(maintainItem);
	    //添加日志
	    customLogService.addLog("车辆基础资料", createTime+"对维修项目进行添加操作", null, user.getFid());
	    //重定向到添加方法
	    return "redirect:/DrivingSys/insertMaintainItem?type=3";
	}
	
	/**
	 * 根据名称查询
	 * @param request
	 * @param fnameL2 名称
	 * @return 返回查询页面
	 */
	@RequestMapping("/queryMaintainItemByFnameL2")
	public String queryMaintainItemByFnameL2(HttpServletRequest request,String fnameL2){
		PageBean<MaintainItem>pb = new PageBean<>();
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
        //去除空格
        fnameL2 = fnameL2.trim();
        if("".equals(fnameL2)){//如果未空，就调用查询的方法
            queryMaintainItem(request, null);
        }else{
            List<MaintainItem> maintainItems = new ArrayList<>();
            try {
                pb = getPageBean(request, user.getFcompanyid(), fnameL2);
                maintainItems = pb.getBeanList();
                //把数据传到页面
                request.setAttribute("pb", pb);
                request.setAttribute("maintainItems", maintainItems);
                request.setAttribute("fnameL2", fnameL2);
            } catch (Exception e) {
                e.printStackTrace();
            }

	    }
	    return "/backHome/basicData/maintainItem/maintainItemList";
	}
	
	/**
	 * 根据fid查询
	 * @param request
	 * @return
	 */
	@RequestMapping("/selectMaintainItemByFid")
	public String selectMaintainItemByFid(HttpServletRequest request,String fid){
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
		//根据fid查询
		MaintainItem maintainItem = maintainItemService.quetyByPrimaryKey(fid);
		//获取所有的修理厂
		List<RepairShop> repairShops = repairShopService.queryRepairShopAll();
		//获取组织
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//把数据传到页面
		request.setAttribute("department", department);
		request.setAttribute("maintainItem", maintainItem);
		request.setAttribute("repairShops", repairShops);
		return "/backHome/basicData/maintainItem/maintainItemUpdate";
	}
	
	/**
	 * 根据fid修改
	 * @param request
	 * @param maintainItem
	 * @return
	 */
	@RequestMapping("/updateMaintainItem")
	public String updateMaintainItem(HttpServletRequest request,MaintainItem maintainItem){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//公司id
		maintainItem.setCfficompanyid(user.getFcompanyid());
		//控制单元id
	    maintainItem.setFcontrolunitid(user.getFcompanyid());
		//获取当前修改时间
		String updateTime = TimeFormat.timeFormat(new Date());
	    //修改时间
		maintainItem.setFlastupdatetime(updateTime);
		//修改人id
		maintainItem.setFlastupdateuserid(user.getFid());
		//修改项目维修
		maintainItemService.modifyMaintainItem(maintainItem);
		//添加日志
	    customLogService.addLog("车辆基础资料", updateTime+"对维修项目进行修改操作", null, user.getFid());
	    //调用查询的方法
        return commonController.skipUrl("/queryMaintainItem/look.action");
    }
	
	/**
     * 根据fid删除
     * @param request
	 * @param deleteId fid
	 * @return 返回查询页面
	 */
	@RequestMapping("/deleteMaintainItemByFid")
	public String deleteMaintainItemByFid(HttpServletRequest request,String deleteId[],String fid){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//删除数据
		if("".equals(fid)|| fid == null){
			for(int i = 0;i<deleteId.length;i++){
				maintainItemService.deleteMaintainItemByFid(deleteId[i]);
			}
		}else{
			maintainItemService.deleteMaintainItemByFid(fid);
		}
		
		//添加日志
	    customLogService.addLog("车辆基础资料", TimeFormat.timeFormat(new Date())+"对维修项目进行删除操作", null, user.getFid());
	    //调用查询的方法
        queryMaintainItem(request, null);
        return "/backHome/basicData/maintainItem/maintainItemList";
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
    public PageBean<MaintainItem> getPageBean(HttpServletRequest request, String companyId, String fnameL2) throws Exception {

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid,t.fnumber,t.fname_l2 fnameL2,t.fsimplename,t.fdescription_l2 fdescriptionL2,");
		psql.append("t.cfprice,c.name createName,u.name updateName,r.fname_l2 repairshop,t.cfmanhours,");
		psql.append("to_char(t.FLASTUPDATETIME,'YYYY-MM-DD HH24:MI:SS') flastupdatetime,");
		psql.append("to_char(t.FCREATETIME,'YYYY-MM-DD HH24:MI:SS') fcreatetime from ct_ds_maintainitem t ");
		psql.append("left join t_e_user c on t.fcreatorid=c.fid left join t_e_user u on t.fcreatorid=u.fid left join ");
        psql.append("ct_ds_repairshop r on t.cfrepairshopid=r.fid where t.fcontrolunitid='" + companyId + "'");
        if (fnameL2 == null || "".equals(fnameL2)) {

        } else {
            psql.append(" and t.fname_l2 like '%" + fnameL2 + "%'");
        }
        psql.append(" order by t.fcreatetime desc");
        int psize=100; //每页显示数
		int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= maintainItemService.selectPage(pindex, psql.toString(), psize);
		PageBean<MaintainItem> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<MaintainItem>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=maintainItemService.selectPageCount(psql);
		return paramMap;		
	}


	/**
	 * 导出Execl
	 *
	 * @param response
	 */
	@RequestMapping("/importMaintainItem")
	public void importMaintainItem(HttpServletResponse response, HttpServletRequest request, String fnameL2) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		List<Object> data = new ArrayList<>();
		//查询数据
        List<MaintainItem> maintainItems = maintainItemService.queryMaintainItemByFnameL2(fnameL2.trim(), user.getFcompanyid());
        for (MaintainItem maintainItem : maintainItems) {
			data.add(maintainItem.getFnumber());//编号
			data.add(maintainItem.getFnameL2());//名称
			data.add(maintainItem.getFsimplename());//保修期
			data.add(maintainItem.getFdescriptionL2());//描述
			data.add(maintainItem.getFcreatetime());//创建时间
			data.add(maintainItem.getFlastupdatetime());//最后修改时间
			data.add(maintainItem.getCreateName());//创建人
			data.add(maintainItem.getUpdateName());//修改人
			data.add(maintainItem.getCfprice());//单价
			data.add(maintainItem.getCfmanhours());//工时
			data.add(maintainItem.getRepairshop());//修理厂
		}

		//头部数据
		String head[] = {"编码", "名称", "保修期", "描述", "创建时间", "最后修改时间","创建人", "修改人","单价","工时","修理厂"};
		//长度
		Integer length[] = {7000, 7000, 5000, 5000, 6200, 6200, 3000, 3000,3000,3000,8000};
		try {
			//导出Excel
			CommonExport.importExcel(response, "修理厂" + TimeFormat.getNowTime2() + ".xls", "修理厂", data, head, length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
